package com.yuyou.tas.terminal.controller;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.yuyou.tas.service.api.admin.entity.AuthUser;
import com.yuyou.tas.service.api.admin.service.AuthUserAPI;
import com.yuyou.tas.service.api.feedback.service.FeedbackCommentAPI;
import com.yuyou.tas.service.api.feedback.vo.resp.UnReadSimpleVo;
import com.yuyou.tas.service.api.lesson.dto.LessonClassPage;
import com.yuyou.tas.service.api.lesson.service.LessonClassAPI;
import com.yuyou.tas.terminal.vo.ReqMTBase;
import com.yuyou.tas.terminal.vo.ReqMU.ClassReqVo;
import com.yuyou.tas.util.bean.LoginRedisObj;
import com.yuyou.tas.util.bean.ResBoolSimpleInfo;
import com.yuyou.tas.util.bean.ReturnResult;
import com.yuyou.tas.util.enums.Channel;
import com.yuyou.tas.util.exception.BusinessException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Api(value="YyfnMTController",description="教师端公共接口")
@Validated
@RestController
@RequestMapping(value = "/api/m/t")
public class YyfnMTController extends BaseController{

	@Autowired
	private StringRedisTemplate stringRedisTemplate;

	@Autowired
	private AuthUserAPI authUserAPI;

	@Autowired
	private FeedbackCommentAPI feedbackCommentAPI;


	@Autowired
	private LessonClassAPI lessonClassAPI;
	
    protected AuthUser getTasUser(String sysCode,Long teacherId,String accessToken,Integer type) throws Exception {    	
    	//TODO remove
		if(type!=null && type.intValue()==Channel.channelE.pc.getValue()){			
			String jsonObj=stringRedisTemplate.opsForValue().get(accessToken);
	        LoginRedisObj obj=JSONObject.parseObject(jsonObj, new TypeReference<LoginRedisObj>() {});
			
			AuthUser authUser=authUserAPI.selectById(obj.getUserId());
			if(authUser==null){
				throw new BusinessException("没找到该用户信息");
			} 
			return authUser;
		}
    	
    	//转换老师用户ID
    	Long authOrganizationId=this.getOrganId(sysCode);
    	AuthUser authUser = authUserAPI.selectByOrgan7OId(teacherId,authOrganizationId);		
    	if(authUser==null){
        	throw new BusinessException("没找到该用户信息");
    	}   	
    	return authUser;
    }
	
	@ApiOperation(value = "查询所在机构老师的班级")
	@ApiImplicitParams({})
	@RequestMapping(value = "/findClass", method = { RequestMethod.GET,
			RequestMethod.POST })
	public ReturnResult<LessonClassPage> findClass(
			HttpServletRequest request,@Validated @ModelAttribute ClassReqVo vo
			) throws Exception {
		//转换老师用户ID
		AuthUser authUser = this.getTasUser(vo.getSysCode(), vo.getTeacherId(),vo.getAccessToken(),vo.getChannel());
		if(authUser == null){
			ReturnResult.fail("找不到用户信息,请联系管理员。");
		}
		ResBoolSimpleInfo<LessonClassPage> resBoolSimpleInfo = lessonClassAPI.findLessonClassByTeacher(authUser.getId() , vo.getSchoolId() , vo.getTrimesterId() ,
																		vo.getSectionId() , vo.getLevelId() , vo.getPageSize() ,vo.getPageIndex());
		if(!resBoolSimpleInfo.isSuccess()){
			return ReturnResult.fail(resBoolSimpleInfo.getMessage());
		}
		//设置未读数目
		if(!CollectionUtils.isEmpty(resBoolSimpleInfo.getData().getList())){
			List<Long> classIds = resBoolSimpleInfo.getData().getList().stream().map(lessonClassDTO -> lessonClassDTO.getId()).collect(Collectors.toList());
			List<UnReadSimpleVo> unReadSimpleVos = feedbackCommentAPI.getTeacherClassUnReadCount(authUser.getId() , classIds);
			if(!CollectionUtils.isEmpty(unReadSimpleVos)){
				Map<Long , UnReadSimpleVo> map = com.yuyou.tas.util.tool.BeanUtils.toMap(unReadSimpleVos , "id");
				resBoolSimpleInfo.getData().getList().forEach(lessonClassDTO -> {
					if(map.containsKey(lessonClassDTO.getId())){
						lessonClassDTO.setUnreadCount(map.get(lessonClassDTO.getId()).getCount());
					}
				});
			}
		}
		return ReturnResult.success(resBoolSimpleInfo.getData());
	}
	
	/*@ApiOperation(value = "查询所在机构班级的学生")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "classId", value = "班级主键", paramType = "query", required = true)})
	@RequestMapping(value = "/findClassStudent", method = { RequestMethod.GET,
			RequestMethod.POST })
	public ReturnResult<List<BaseTrimester>> findClassStudent(
			HttpServletRequest request,@Validated @ModelAttribute ReqMTBase reqMTBase,@NotNull(message = "classId不能为空") Long classId) throws Exception {
		return ReturnResult.success("");
	}*/


	@ApiOperation(value = "查询班级学生人数")
	@ApiImplicitParams({})
	@RequestMapping(value = "/findClassStuCount", method = { RequestMethod.GET,
			RequestMethod.POST })
	public ReturnResult<Integer> findClassStuCount(@Validated @ModelAttribute ReqMTBase reqMTBase, @NotNull(message = "班级ID不能为空") Long classId
	) throws Exception {
		//转换老师用户ID
		AuthUser authUser = this.getTasUser(reqMTBase.getSysCode(), reqMTBase.getTeacherId(),reqMTBase.getAccessToken(),reqMTBase.getChannel());
		if(authUser == null){
			ReturnResult.fail("找不到用户信息,请联系管理员。");
		}
		Integer count = lessonClassAPI.getStudentCountByClassId(classId);
		return ReturnResult.success(count);
	}
	
}
